"""
OKX API 数据模型
"""
from dataclasses import dataclass
from typing import Optional, List
from datetime import datetime


@dataclass
class KlineData:
    """K线数据"""
    timestamp: int
    open: float
    high: float
    low: float
    close: float
    volume: float
    quote_volume: float

    @property
    def time(self) -> datetime:
        """转换为datetime"""
        return datetime.fromtimestamp(self.timestamp / 1000)


@dataclass
class Order:
    """订单数据"""
    order_id: str
    symbol: str
    order_type: str  # limit/market
    side: str  # buy/sell
    price: float
    quantity: float
    status: str  # pending/filled/cancelled
    filled_qty: float
    filled_price: float
    timestamp: int
    fee: float = 0.0


@dataclass
class Position:
    """持仓数据"""
    symbol: str
    side: str  # long/short
    quantity: float
    avg_price: float
    current_price: float
    unrealized_pnl: float
    leverage: float = 1.0

    @property
    def value(self) -> float:
        """持仓价值"""
        return self.quantity * self.current_price

    @property
    def pnl_ratio(self) -> float:
        """盈亏率 (%)"""
        if self.avg_price == 0:
            return 0.0
        if self.side == "long":
            return (self.current_price - self.avg_price) / self.avg_price * 100
        else:
            return (self.avg_price - self.current_price) / self.avg_price * 100


@dataclass
class AccountBalance:
    """账户余额"""
    currency: str
    balance: float
    available: float
    frozen: float

    @property
    def total(self) -> float:
        return self.balance


@dataclass
class TradeResult:
    """交易结果"""
    success: bool
    order_id: Optional[str] = None
    message: str = ""
    order: Optional[Order] = None
    timestamp: int = 0
